package org.hijava.iplooking;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class DataUpload extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		doGet(req, resp);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		ServletFileUpload upload = new ServletFileUpload();
		upload.setHeaderEncoding("UTF-8");
		byte[] cache=new byte[40*1024];
		int len=0;
		FileItemIterator iter;
		try {
			iter = upload.getItemIterator(req);

			while (iter.hasNext()) {
				FileItemStream item = (FileItemStream) iter.next();
				if(!item.isFormField()){
					InputStream stream = item.openStream();
					len=stream.read(cache);
					break;
				}
			}

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Scanner scan=new Scanner(new String(cache,0,len,"UTF-8")).useDelimiter("\n");
		scan.next();
		while(scan.hasNext()){
			String line=scan.next();
			IP ip=new IP(line);
			pm.makePersistent(ip);
		}
		pm.close();
	}
}
